﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DAWSharp.DSP.Delay
{
    public class Delay
    {
        internal int bufferSamps;
        internal float[] delayBuffer;
        internal int i_pos;
        internal int o_pos;

        internal Delay()
        {

        }

        public Delay(int bufferSize)
        {
            bufferSamps = bufferSize;
            delayBuffer = new float[bufferSamps];

            i_pos = 1;
            o_pos = 0;
        }

        public float Process(float sample, float feedback, int delaySamples)
        {
            float delayOutput = delayBuffer[o_pos];
            delayBuffer[i_pos] = sample + (feedback * delayOutput);
            Update(delaySamples);

            return delayOutput;
        }

        internal void Update(int Samples)
        {
            if (i_pos > o_pos)
            {
                o_pos = i_pos - Samples;
            }

            if (i_pos < o_pos)
            {
                o_pos = (bufferSamps + i_pos) - Samples;
            }

            if (i_pos == Samples)
            {
                o_pos = bufferSamps;
            }

            if (i_pos <= (Samples - 1))
            {
                o_pos = bufferSamps - (Samples - i_pos);
            }

            if (i_pos == 0)
            {
                o_pos = bufferSamps - Samples;
            }

            if (o_pos == bufferSamps)
            {
                i_pos = Samples;
            }

            i_pos++;

            if (i_pos == bufferSamps)
            {
                i_pos = 0;
            }
            if (o_pos == bufferSamps)
            {
                o_pos = 0;
            }
        }
    }
}
